package com.uroad.lib.activity;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.uroad.lib.R;
import com.uroad.lib.data.Constant;
import com.uroad.lib.http.OkHttpUtils;
import com.uroad.lib.http.builder.PostFormBuilder;
import com.uroad.lib.http.callback.StringCallback;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.activity.ActivityUtil;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.net.NetWorkUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by jiadong on 2016/11/10.
 */
public abstract class BaseUroadActivity extends AppCompatActivity {

    private FrameLayout flBaseContent, flBaseLoad;
    private LinearLayout llBaseLeft, llBaseRight, llBaseRefresh;
    private Button btnBaseLeft;
    private TextView tvBaseTitle, tvBaseRight, tvBaseRefresh, tvBaseBack;
    private ImageView ivBaseLoad;
    private TextView tvBaseLoad;
    private View baseTitle;
    private boolean showNoNetPage = false;
    private boolean showErrorPage = false;
    private boolean showNoNetToast = true;
    private boolean showErrorToast = true;

    private void assignViews() {
        flBaseContent = (FrameLayout) findViewById(R.id.flBaseContent);
        flBaseLoad = (FrameLayout) findViewById(R.id.flBaseLoad);
        llBaseLeft = (LinearLayout) findViewById(R.id.llBaseLeft);
        tvBaseRight = (TextView) findViewById(R.id.tvBaseRight);
        llBaseRight = (LinearLayout) findViewById(R.id.llBaseRight);
        btnBaseLeft = (Button) findViewById(R.id.btnBaseLeft);
        tvBaseTitle = (TextView) findViewById(R.id.tvBaseTitle);
        baseTitle = findViewById(R.id.baseTitle);

        llBaseLeft.setOnClickListener(onClickListener);
        llBaseRight.setOnClickListener(onClickListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_base_uroad);
        assignViews();
        addBaseLoadView();
    }

    /**
     * 网络请求
     *
     * @param methodUrl url方法名eg."/sys/getFileVer"
     * @param params    请求参数
     * @param id
     */

    public void doRequest(String methodUrl, HashMap<String, Object> params, String id) {
        doPost(Constant.BASE_URL + methodUrl, params, id);
    }

    /**
     * 网络请求
     *
     * @param methodUrl url方法名eg."/sys/getFileVer"
     * @param params    请求参数
     */
    public void doRequest(String methodUrl, HashMap params) {
        doPost(Constant.BASE_URL + methodUrl, params, methodUrl);
    }

    /***
     * 网络请求
     *
     * @param methodUrl url 完整的URL请求
     * @param params    请求参数
     * @param id
     */
    public void doAllUrlRequest(String methodUrl, HashMap<String, Object> params, String id) {
        doPost(methodUrl, params, id);
    }

    public void doPost(String url, HashMap<String, Object> params, String id) {
        if (!NetWorkUtil.checkNet(this)) {
            OnHttpNetWork(id);
            return;
        }
        PostFormBuilder postFormBuilder = OkHttpUtils.post();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                postFormBuilder.addParams(entry.getKey(), entry.getValue() + "");
            }
        }
        postFormBuilder.url(url)
                .id(id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, String id) {
                        OnHttpFailure(id);
                    }

                    @Override
                    public void onResponse(String response, String id) {
                        try {
                            OnHttpTaskComplete(response, id);
                        } catch (Exception e) {
                            OnHttpFailure(id);
                        }
                    }
                });
    }

    public void setTitle(String title) {
        tvBaseTitle.setText(title);
    }

    public void setTitleTextColor(int color) {
        tvBaseTitle.setTextColor(color);
    }

    public Button getLeftButton() {
        return btnBaseLeft;
    }

    public void setLeftBtn(int res) {
        btnBaseLeft.setBackgroundResource(res);
    }

    public void setTitleBackground(int res) {
        baseTitle.setBackgroundResource(res);
    }

    public void setTitleBackgroundColor(int color) {
        baseTitle.setBackgroundColor(color);
    }

    public void setNoTitle() {
        baseTitle.setVisibility(View.GONE);
    }

    public TextView getRight() {
        return tvBaseRight;
    }

    public void setRightText(String text, int res) {
        llBaseRight.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(text)) {
            tvBaseRight.setText(text);
        }else{
            tvBaseRight.setText("");
        }
        if (res > 0) {
            Drawable drawable = getResources().getDrawable(res);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvBaseRight.setCompoundDrawables(drawable, null, null, null);
        }else{
            tvBaseRight.setCompoundDrawables(null, null, null, null);
        }
    }

    public void setBaseContentLayout(int layoutResId) {
        flBaseContent.removeAllViews();
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(layoutResId, null);
        flBaseContent.addView(v);
    }

    public void setBaseContentLayoutWithoutTitle(int layoutResId) {
        baseTitle.setVisibility(View.GONE);
        setBaseContentLayout(layoutResId);
    }

    public void setBaseContentLayout(View v) {
        flBaseContent.removeAllViews();
        flBaseContent.addView(v);
    }

    public void setBaseContentLayoutWithoutTitle(View view) {
        baseTitle.setVisibility(View.GONE);
        setBaseContentLayout(view);
    }

    protected void showLongToast(String pMsg) {
        if (!TextUtils.isEmpty(pMsg))
            Toast.makeText(this, pMsg, Toast.LENGTH_LONG).show();
//            DialogHelper.showShortTost(this, pMsg);
    }

    protected void showShortToast(String pMsg) {
        if (!TextUtils.isEmpty(pMsg))
            Toast.makeText(this, pMsg, Toast.LENGTH_SHORT).show();
//            DialogHelper.showShortTost(this, pMsg);
    }

    protected void showMsgToast(JSONObject object) {
        String msg = FastJsonUtils.getErrorString(object, "msg");
        if (!TextUtils.isEmpty(msg)) {
            showShortToast(msg);
        }
    }

    protected void showErrorToast(JSONObject object) {
        String msg = FastJsonUtils.getErrorString(object, "msg");
        if (!TextUtils.isEmpty(msg)) {
            showShortToast(msg);
        }
    }

    protected void openActivity(Class<?> pClass) {
        ActivityUtil.openActivity(this, pClass);
    }

    protected void openActivity(Class<?> pClass, Bundle pBundle) {
        ActivityUtil.openActivity(this, pClass, pBundle);
    }

    protected void openHistoryActivity(Class<?> pClass) {
        ActivityUtil.openActivityFromHistory(this, pClass);
    }

    protected void openActivity(String pAction, Bundle pBundle) {
        ActivityUtil.openActivity(this, pAction, pBundle);
    }


    protected void addBaseLoadView() {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.view_baseload, null);
        flBaseLoad.addView(view);
        ivBaseLoad = (ImageView) view.findViewById(R.id.ivBaseLoad);
        tvBaseLoad = (TextView) view.findViewById(R.id.tvBaseLoad);
        llBaseRefresh = (LinearLayout) view.findViewById(R.id.llBaseRefresh);
        tvBaseRefresh = (TextView) view.findViewById(R.id.tvBaseRefresh);
        tvBaseBack = (TextView) view.findViewById(R.id.tvBaseBack);

        flBaseLoad.setOnClickListener(onClickListener);
        ivBaseLoad.setOnClickListener(onClickListener);
        tvBaseRefresh.setOnClickListener(onClickListener);
        tvBaseBack.setOnClickListener(onClickListener);
    }

    /**
     * 设置加载、无网络、接口调用失败的信息
     *
     * @param res  显示的图片
     * @param text 正在加载的文字
     */
    public void setPagePic(int res, String text) {
        flBaseLoad.setVisibility(View.VISIBLE);
        ivBaseLoad.setImageResource(res);
        if (!TextUtils.isEmpty(text)) {
            tvBaseLoad.setVisibility(View.VISIBLE);
            tvBaseLoad.setText(text);
        } else {
            tvBaseLoad.setVisibility(View.GONE);
        }
    }

    /**
     * 默认加载页面
     **/
    protected void setPageLoading() {
        setPagePic(R.drawable.ic_base_loading, "正在加载...");
        llBaseRefresh.setVisibility(View.GONE);
    }

    protected void setPageEndLoading() {
        flBaseLoad.setVisibility(View.GONE);
    }

    protected void setPageNetworkError() {
        setPagePic(R.drawable.ic_base_no_net, "");
        llBaseRefresh.setVisibility(View.GONE);
    }

    protected void setPageLoadNodata() {
        setPagePic(R.drawable.ic_base_error, "");
        llBaseRefresh.setVisibility(View.VISIBLE);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int i = view.getId();
            if (i == R.id.llBaseLeft) {
                Back();
            } else if (i == R.id.llBaseRight) {
                onRightClick(view);
            } else if (i == R.id.ivBaseLoad) {
                if (tvBaseLoad.getVisibility() == View.GONE && llBaseRefresh.getVisibility() == View.GONE) {
                    onBaseRefresh(view);
                }
            } else if (i == R.id.tvBaseRefresh) {
                onBaseRefresh(view);
            } else if (i == R.id.tvBaseBack) {
                onBaseBack(view);
            }
        }
    };

    public void Back() {
        onBackPressed();
    }

    protected void onRightClick(View v) {

    }

    protected void onBaseRefresh(View v) {
    }

    protected void onBaseBack(View v) {

    }

    /**
     * 设置是否显示接口超时或错误的提示页面
     *
     * @param showErrorPage
     */
    public void setShowErrorPage(boolean showErrorPage) {
        this.showErrorPage = showErrorPage;
    }

    /**
     * 设置是否显示无网络的提示页面
     *
     * @param showNoNetPage
     */
    public void setShowNoNetPage(boolean showNoNetPage) {
        this.showNoNetPage = showNoNetPage;
    }

    /**
     * 设置是否显示接口超时的Toast提示
     *
     * @param showErrorToast
     */
    public void setShowErrorToast(boolean showErrorToast) {
        this.showErrorToast = showErrorToast;
    }

    /**
     * 设置是否显示无网络的Toast提示
     *
     * @param showNoNetToast
     */
    public void setShowNoNetToast(boolean showNoNetToast) {
        this.showNoNetToast = showNoNetToast;
    }

    /**
     * 没有网络回调
     *
     * @param msg
     */
    public void OnHttpNetWork(String msg) {
        if (showNoNetPage) {
            setPageNetworkError();
        }
        if (showNoNetToast) {
            showShortToast("网络异常，请检查网络");
        }
    }

    /**
     * 请求数据失败回调
     *
     * @param msg
     */
    public void OnHttpFailure(String msg) {
        if (showErrorPage) {
            setPageLoadNodata();
        }
        if (showErrorToast) {
            showShortToast("系统繁忙，请稍后再试");
        }
    }

    /**
     * 请求数据完成回调
     *
     * @param result 返回数据
     * @param id     返回数据类型
     */
    public void OnHttpTaskComplete(String result, String id) {
        LogUtil.i("BaseUroadActivity", "接口：" + id + "\n返回：" + result);
    }

}
